<template>
    <div class="chat-container">
      <h1>WebSocket 聊天室</h1>
      <div class="status">
        连接状态: <span :class="status">{{ statusText }}</span>
      </div>
      
      <div class="message-list">
        <div v-for="(msg, index) in messages" :key="index" class="message">
          <span class="time">{{ msg.timestamp }}</span>
          <span class="from">{{ msg.from }}:</span>
          <span class="content">{{ msg.content }}</span>
        </div>
      </div>
      
      <div class="input-area">
        <input v-model="currentMessage" @keyup.enter="sendMessage" placeholder="输入消息..." />
        <button @click="sendMessage" :disabled="status !== 'CONNECTED'">发送</button>
      </div>
    </div>
  </template>
  
  <script lang="ts">
  import { defineComponent, ref, computed, onMounted, onUnmounted } from 'vue';
  import { useWebSocket } from '../services/websocket_direct'
  
  export default defineComponent({
    name: 'ChatView',
    setup() {
      const { status, messages, connect, disconnect, subscribe, send } = useWebSocket();
      const currentMessage = ref('');
      const username = ref('用户' + Math.floor(Math.random() * 1000));
      
      // 状态显示文本
      const statusText = computed(() => {
        switch (status.value) {
          case 'CONNECTED': return '已连接';
          case 'CONNECTING': return '连接中...';
          case 'DISCONNECTED': return '已断开';
          case 'ERROR': return '连接错误';
          default: return '未知状态';
        }
      });
      
      // 发送消息
      const sendMessage = () => {
        if (currentMessage.value.trim() && status.value === 'CONNECTED') {
          const timestamp = formatDate(new Date());
          const message={
            from: username.value,
            content: currentMessage.value,
            timestamp
          };
          console.log('message',message);
          
          send('/app/chat',message );
          currentMessage.value = '';
        }
      };
      
      // 初始化连接
      onMounted(() => {
        let requestUrl='http://localhost:8080/ws';
        // requestUrl="http://localhost:8080/ws/";
        connect(requestUrl, () => {
          // 订阅消息
          subscribe('/topic/messages', (message) => {
            const msg = JSON.parse(message.body);
            messages.value.push(msg);
          });
        });
      });
      
      // 组件卸载时断开连接
      onUnmounted(() => {
        disconnect();
      });
      
      return {
        status,
        statusText,
        messages,
        currentMessage,
        sendMessage
      };
    }
  });

  function formatDate(date:Date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

  </script>
  
  <style scoped>
  .chat-container {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    font-family: Arial, sans-serif;
  }
  
  .status {
    margin: 10px 0;
  }
  
  .status span {
    padding: 2px 5px;
    border-radius: 3px;
  }
  
  .status .CONNECTED {
    background-color: #4CAF50;
    color: white;
  }
  
  .status .CONNECTING {
    background-color: #FFC107;
    color: black;
  }
  
  .status .DISCONNECTED, .status .ERROR {
    background-color: #F44336;
    color: white;
  }
  
  .message-list {
    height: 400px;
    border: 1px solid #ddd;
    padding: 10px;
    overflow-y: auto;
    margin-bottom: 10px;
    background-color: #f9f9f9;
  }
  
  .message {
    margin-bottom: 8px;
    padding: 5px;
    border-bottom: 1px solid #eee;
  }
  
  .time {
    color: #999;
    font-size: 0.8em;
    margin-right: 10px;
  }
  
  .from {
    font-weight: bold;
    margin-right: 5px;
  }
  
  .input-area {
    display: flex;
  }
  
  .input-area input {
    flex: 1;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px 0 0 4px;
  }
  
  .input-area button {
    padding: 8px 15px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 0 4px 4px 0;
    cursor: pointer;
  }
  
  .input-area button:disabled {
    background-color: #cccccc;
    cursor: not-allowed;
  }
  </style>